//
//  Register_Vc.swift
//  MikerShop
//
//  Created by eme on 2016/11/23.
//  Copyright © 2016年 eme. All rights reserved.
//

/*
 owner:cy
 update:2016年11月23日11:35:21
 info: 注册界面
 */
import RxSwift
import Presentr
import UtilCore
import RickonCore
import BrandonCore

class Register_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var phone_Border_V: UIView!
    @IBOutlet weak var phone_Tf: UITextField!
    @IBOutlet weak var messageCode_Border_V: UIView!
    @IBOutlet weak var messageCode_Tf: UITextField!
    @IBOutlet weak var messageCode_Btn: UIButton!
    @IBOutlet weak var registerCode_Border_V: UIView!
    @IBOutlet weak var registerCode_Tf: UITextField!
    
    @IBOutlet weak var ty_Btn: UIButton!
    
    @IBOutlet weak var xy_Btn: UIButton!
    @IBOutlet weak var next_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var manageVm :Register_Vm?
    /// 计时器
    var countdownTimer: Timer?
    var remainingSeconds: Int = 0 {
        willSet {
            messageCode_Btn.setTitle("\(newValue)秒后重新获取", for: .normal)
            if newValue <= 0 {
                messageCode_Btn.setTitle("获取验证码", for: .normal)
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Register_Vc.updateTime(_:)), userInfo: nil, repeats: true)
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            
            messageCode_Btn.isEnabled = !newValue
        }
    }
    let presenter: Presentr = {
        let presenter = Presentr(presentationType: .alert)
        presenter.presentationType = .popup
        return presenter
    }()
    
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier { // 检查是否 nil
            switch identifier {
            case "SetPwd_Vc":
                if let vc = segue.destination as? SetPwd_Vc {
                    vc.glshop = sender as? GlShopModel
                }
            default: break
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.next_Btn.changeBorderColor(UIColor.clear, cornerRadius: 3.5)
        self.next_Btn.backgroundColor = UIColor.clear
        self.next_Btn.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.btn.disabled)
        self.phone_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.messageCode_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.registerCode_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.messageCode_Btn.setBackgroundImage(Theme.jonSnow.msgcode_bg_btn.getImage(), for: .normal)
        self.messageCode_Btn.setBackgroundImage(Theme.jonSnow.msgcode_font_btn.getImage(), for: .disabled)
        self.messageCode_Btn.setTitleColor(Theme.jonSnow.msgcode_font_btn, for: .normal)
        self.messageCode_Btn.setTitleColor(Theme.jonSnow.msgcode_bg_btn, for: .disabled)
        self.messageCode_Btn.setTitle("获取验证码", for: .normal)
        self.phone_Tf.changePlaceholder("请输入手机号",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.registerCode_Tf.changePlaceholder("如果有邀请码，请输入邀请码",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.messageCode_Tf.changePlaceholder("请输入短信验证码",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.ty_Btn.rx.tap.subscribe(onNext: { [unowned self] ( _ ) in
            self.ty_Btn.isSelected = !self.ty_Btn.isSelected
        }).disposed(by: disposeBag)
        self.xy_Btn.rx.tap.subscribe(onNext: { [unowned self] ( _ ) in
            let agreementVc: Agreement_Vc = JonSnowCore.storyboard.instantiateViewController()
            self.customPresentViewController(self.presenter, viewController: agreementVc, animated: true, completion: nil)
        }).disposed(by: disposeBag)
        /// tyTaps : 刚初始化界面时需要手动的触发下 tytaps事件流否则combineLatest 在合并同意事件时第一次没有任何相应
        self.manageVm = Register_Vm(input: (
            phone: phone_Tf.rx.text.orEmpty.asObservable(),
            msgCode: messageCode_Tf.rx.text.orEmpty.asObservable(),
            registerCode:registerCode_Tf.rx.text.orEmpty.asObservable(),
            nextTaps: next_Btn.rx.tap.asObservable(),
            tyTaps: Observable.of(Observable.just(false), ty_Btn.rx.tap.asObservable().map{ _ in return self.ty_Btn.isSelected }).merge(),
            getMsgCodeTaps: messageCode_Btn.rx.tap.asObservable()
            ), validationService: RegisterImplementations())
        self.manageVm?.signupEnabled
            .subscribe(onNext: { [unowned self] (valid) in
                self.next_Btn.isEnabled = valid
            }).addDisposableTo(disposeBag)
        self.manageVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.manageVm?.signingIn.bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.manageVm?.nextSuccess
            .subscribe(onNext: { [unowned self] (rel) in
                self.performSegue(withIdentifier: "SetPwd_Vc", sender: rel)
            }).addDisposableTo(disposeBag)
        self.manageVm?.validatedPhone
            .subscribe(onNext: {[unowned self] (result) in
                if result.isValid && self.remainingSeconds == 0{
                    self.messageCode_Btn.isEnabled = true
                }else{
                    self.messageCode_Btn.isEnabled = false
                }
            }).addDisposableTo(disposeBag)
        self.manageVm?.sendMsgSuccess
            .subscribe(onNext: {[unowned self] (json) in
                if UtilCore.sharedInstance.isDebug{
                    self.view.toast(json.stringValue)
                }
                self.isCounting = true
            }).addDisposableTo(disposeBag)
        self.messageCode_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.view.endEditing(true)
            })
            .disposed(by: disposeBag)
        self.next_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.view.endEditing(true)
            })
            .disposed(by: disposeBag)
    }
}
